package com.shijiu.aop;

import com.shijiu.annotation.RepeatSubmit;
import com.shijiu.common.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author xlj
 * @Date Created in  2023/4/11 11:40
 * @DESCRIPTION: 限制 一段时间可以请求的次数
 * @Version V1.0
 */
@Aspect
@Component
public class RepeatSubmitAspect {

    private static final Map<String, Long> REQUEST_TIME_MAP = new ConcurrentHashMap<>();

    @Around("@annotation(repeatSubmit)")
    public Object around(ProceedingJoinPoint point, RepeatSubmit repeatSubmit) throws Throwable {
        Object result = null;

        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();

        String key = method.getName() + ":" + Arrays.toString(point.getArgs());
        Long requestTime = REQUEST_TIME_MAP.get(key);
        long currentTime = System.currentTimeMillis();

        if (requestTime == null || currentTime - requestTime >= repeatSubmit.interval()) {
            result = point.proceed();
            REQUEST_TIME_MAP.put(key, currentTime);
        } else {
            return Result.fail(201,repeatSubmit.message());
        }

        return result;
    }
}
